﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace Mvc4Demo.Core
{
    //http://stackoverflow.com/questions/8284207/asp-net-mvc-implement-custom-validator-use-iclientvalidatable

    public class ClientValidateAttribute : ValidationAttribute, IClientValidatable
    {
        private readonly string _propertyName;

        public ClientValidateAttribute(string propertyName)
        {
            _propertyName = propertyName;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            return value != null
                       ? ValidationResult.Success
                       : new ValidationResult(String.Format(ErrorMessageString, validationContext.DisplayName));
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
                {
                    ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
                    ValidationType = "clientvalidate"
                };

            rule.ValidationParameters["propertyname"] = metadata.PropertyName;
            rule.ValidationParameters["otherpropertyname"] = "Your other property";
            rule.ValidationParameters["othervalue"] = "Your other value";

            yield return rule;
        }
    }
}